package controller

import (
	"context"
	"github.com/RaymondCode/simple-demo/config"
	"github.com/RaymondCode/simple-demo/entity/myerr"
	"github.com/RaymondCode/simple-demo/entity/param"
	"github.com/RaymondCode/simple-demo/entity/response"
	"github.com/RaymondCode/simple-demo/middleware"
	serviceimpl "github.com/RaymondCode/simple-demo/service/impl"
	"github.com/RaymondCode/simple-demo/util/webutil"
	"github.com/cloudwego/hertz/pkg/app"
	"strconv"

	"log"
	"net/http"
)

func Comment(ctx context.Context, c *app.RequestContext) {
	var commentParam param.Comment
	var err error
	commentParam.CommentId, err = strconv.Atoi(c.Query("comment_id"))
	commentParam.CommentText = c.Query("comment_text")
	commentParam.VideoID, err = strconv.Atoi(c.Query("video_id"))
	commentParam.ActionType, err = strconv.Atoi(c.Query("action_type"))
	// 参数校验
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusBadRequest, response.ArgumentError(myerr.ArgumentInvalid(webutil.GetValidMsg(err, commentParam))))
		return
	}
	// 从ThreadLocal中获取用户ID
	userId, err := strconv.Atoi(middleware.ThreadLocal.Get().(map[string]string)[config.Config.ThreadLocal.Keys.UserId])
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusInternalServerError, response.SystemError)
	}
	// 获取单例service对象，进行数据持久化
	err = serviceimpl.NewCommentServiceInstance().Comment(&commentParam, userId)
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusInternalServerError, response.SystemError)
		return
	}
	c.JSON(http.StatusOK, response.Ok)
}

func CommentList(ctx context.Context, c *app.RequestContext) {
	var commentListParam param.CommentList
	var err error
	commentListParam.VideoId, err = strconv.Atoi(c.Query("video_id"))
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusBadRequest, response.ErrorResponse(myerr.ArgumentInvalid(webutil.GetValidMsg(err, commentListParam))))
		return
	}
	commentList, err := serviceimpl.NewCommentServiceInstance().CommentList(commentListParam.VideoId)
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusInternalServerError, response.SystemError)
		return
	}
	c.JSON(http.StatusOK, response.CommentList{
		Response: response.Ok,
		Data:     *commentList,
	})
}
